<?php

namespace app\home\controller;

/*
 * 志愿者功能
 */

use DateTime;
use Qcloud\Sms\SmsMultiSender;
use think\Controller;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\response\Json;

class Volun extends Controller
{

    // 短信应用SDK AppID
    public $appid = 1400576972;

    // 短信应用SDK AppKey
    public $appkey = "a699bc79e26650c3f140588900e4d362";

    // 短信模板ID，需要在短信应用中申请
    public $templateId = 1140449;

    // 签名
    public $smsSign = "忆流年";

    public function UserAdmir() //用户管理模块
    {
        if (!$this->Identity()) {
            $this->error('你无权操作');
        }
        return $this->fetch('voluntary/UserAdmin');
    }

    /**
     * 身份认证
     * @return bool 是否有权限
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    private function Identity()
    {
        $SafeCode = cookie('SafeCode');
        $UserData = Db::name('users')->field('password', true)->where('SafeCode', $SafeCode)->find();
        if (in_array($UserData['auth'], [2, 3, 4])) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 用户管理接口
     * @return Json 用户信息
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function UserJson()
    {
        if (!$this->Identity()) {
            return json(['result' => 'error']);
        }
        $SafeCode = cookie('SafeCode');
        $PersonData = \db('users')->where('SafeCode', $SafeCode)->find();

        switch ($PersonData['auth']) {
            //管理员看到所有人
            case 3:
                $UserList = \db('users')->field('password', true)->select();
                break;

            //会长只能看自己院的人
            case 2:
                $UserList = \db('users')->where('college', $PersonData['college'])->field('password', true)->select();
                break;

            //部长只能管自己院自己部门的人
            case 4:
                $UserList = \db('users')->where(['college' => $PersonData['college'], 'department' => $PersonData['department']])->field('password', true)->select();
        }

        return json($UserList);
    }

    public function DeleteUser()   //删除用户
    {
        if (!$this->Identity()) {
            return json(['result' => 'error']);
        }
        $SafeCode = cookie('SafeCode');
        $auth = \db('users')->where('SafeCode', $SafeCode)->find()['auth'];
        if ($auth != 3) {
            return json(['result' => 'error', 'msg' => '非管理员无法删除']);
        }


        $data = file_get_contents('php://input');
        $data = json_decode($data, true);
        $delete_list = array();
        foreach ($data as $datum) {
            $one = Db::name('users')->where('Id', $datum['Id'])->find();
            if ($one['active'] == 0)
                $delete_list[] = $datum['Id'];
        }
        $sql = Db::name('users')->delete($delete_list);
        if ($sql) {
            Monitor('删除了用户');
            return json(['result' => 'success']);
        } else {
            return json(['result' => 'error']);
        }
    }

    public function EditUser()  //用户编辑
    {
        //权限过滤
        if (!$this->Identity()) {
            $this->error('你无权操作');
        }
        $Edit = input('post.');
        $Id = $Edit["Id"];
        $Field = $Edit['field'];  //要修改的字段
        $down = false;    //是否为自己降级


        //编辑对象信息
        $EditUser = \db('users')->where('Id', $Id)->find();

        //编辑人信息
        $SafeCode = cookie('SafeCode');
        $PersonData = \db('users')->where('SafeCode', $SafeCode)->find();


        //对当前用户权限进行验证,管理员拥有最高权限，无需验证
        switch ($PersonData['auth']) {
            //干事，普通学生，主席
            case 5:
            case 0:
            case 1:
                return json(["result" => "error", "msg" => "非法操作"]);

            //会长
            case 2:
                if ($EditUser['college'] != $PersonData['college'])
                    return json(["result" => "error", "msg" => "无权操作其他学院学生"]);
                elseif ($EditUser['auth'] == 1 || $EditUser['auth'] == 3)
                    return json(["result" => "error", "msg" => "权限不够"]);
                break;

            //部长
            case 4:
                if ($EditUser['college'] != $PersonData['college'])
                    return json(["result" => "error", "msg" => "无权操作其他学院学生"]);
                elseif (!(($EditUser['auth'] == 0 || $EditUser['auth'] == 5) && $PersonData['department'] == $EditUser['department']))
                    return json(["result" => "error", "msg" => "无法操作非本部学生"]);
                break;
        }


        //如果修改了学院，就更新专业库信息
        if ($Field == "college") {
            $CollegeData = Db::name('college')->where("college_name", $Edit[$Field])->find();
            if (empty($CollegeData)) {
                db('college')->insert(["college_name" => $Edit[$Field]]);
            }
        }

        //如果修改了专业，就更新专业库信息
        if ($Field == "major") {
            $MajorData = Db::name('major')->where("major_name", $Edit[$Field])->find();
            if (empty($CollegeData)) {
                Db::name('major')->insert(["major_name" => $Edit[$Field]]);
            }
        }


        /*
             * 1、管理员有最高权限，可以随意修改
             * 2、主席无特别任命权限（作普通干事处理）
             * 3、会长只能任命本院会长以下权限
             *    会长任命完部长后，原部长不会出现变化，需要手动任命
             *    会长任命完会长后，自身权限变为普通学生（换届操作）
             * pass:网站第一任会长由管理员授权，以后增加或者减少会长数量均由管理员操作
             * 4、部长只能任命同学为该部门干事，且任命后不能修改
             *    部长不能修改已经有部门的同学的信息，即只能管理本院普通学生和本院本部干事
             * 5、干事、普通学生不可进行用户管理
             */
        //如果修改了权限
        if ($Field == 'auth') {
            $auth = $Edit[$Field];    //请求修改的权限


            if ($EditUser['auth'] == 3)
                return json(["result" => "error", "msg" => "无权修改管理员的权限"]);

            //确认当前用户拥有的修改权限
            switch ($PersonData['auth']) {
                //会长
                case 2:
                    if ($auth == 1 || $auth == 3 || $auth == 2)
                        return json(["result" => "error", "msg" => "无权操作"]);
                    elseif ($auth == 2)
                        $down = true; //授予会长权限后自身降级
                    break;

                //部长
                case 4:
                    if ($auth != 5 && $auth != 0)
                        return json(["result" => "error", "msg" => "无权操作"]);
                    break;
            }


        }

        //过滤重要信息
        if (!in_array($Field, ["password", "Id", "username", "qq", "SafeCode", "active", "ActiveCode"])) {
            //为自己降级
            if ($down)
                db('users')->where('SafeCode', $SafeCode)->update(['auth' => '0']);


            $result = Db::name('users')->where('Id', $Id)->update([$Field => $Edit[$Field]]);
            if ($result) {
                Monitor('编辑了用户的信息');
                return json(["result" => "success"]);
            } else {
                return json(["result" => "error", "msg" => "未知错误"]);
            }
        } else {
            return json(["result" => "error", "msg" => "非法操作"]);
        }

    }

    public function Memo()  //内部通知显示
    {
        if (!$this->Identity()) {
            $this->error('你无权操作');
        }

        return $this->fetch('voluntary/Memo');
    }

    public function toMailJson()    //可发件人信息接口
    {
        if (!$this->Identity()) {
            $this->error('你无权操作');
        }
        $AllUser = Db::name("users")->field('username,name,college,major,department')->select();
        $toMail[] = [
            "type" => "用户列表",
            "data" => $AllUser,
        ];

        $AllVolu = Db::name("users")->field('username,name,college,major,department')->where('auth', '<>', 0)->select();
        $toMail[] = [
            "type" => "青协成员",
            "data" => $AllVolu
        ];

        $College = Db::name("college")->select();
        foreach ($College as $key => $item) {
            $College[$key]["username"] = $College[$key]["college_name"] . "-青协";

            $College[$key]["name"] = $College[$key]["college_name"] . "-青协";
        }
        $toMail[] = [
            "type" => "以下学院青协成员",
            "data" => $College
        ];
        foreach ($College as $key => $item) {
            $College[$key]["username"] = $College[$key]["college_name"] . "-全体";
            $College[$key]["name"] = $College[$key]["college_name"] . "-全体";
        }
        $toMail[] = [
            "type" => "以下学院全院同学",
            "data" => $College
        ];


        return json($toMail);
    }

    /*
     * 内部通知相关操作事宜
     */

    public function SendMemo()   //通知执行接口
    {
        if (!$this->Identity())
            return json(["msg" => "你无权操作"]);

        ini_set("max_execution_time", '0');
        $input = input('post.');
        $title = $input["title"];
        $content = $input["content"];


        //获取用户的信息
        $SafeCode = cookie('SafeCode');
        $PersonData = Db::name('users')->where('SafeCode', $SafeCode)->find();
        $uid = $PersonData["Id"];
        $fromUser = $PersonData["name"];
        $randCode = GetRandStr(20);   //获取随机码


        $count = \db('message')
            ->group('code')
            ->where('uid', $uid)
            ->whereTime('time', '>=', date('Y-m-d'))
            ->whereTime('time', '<', date('Y-m-d', time() + 24 * 3600))
            ->count();

        if ($count >= C('limit_msg') && in_array($PersonData['auth'], [5, 0]))
            return json(["msg" => "每日只能发送" . C('limit_msg') . "条信息"]);

        //将发送的邮件存储到数据库
        $MsgId = Db::name('message')->insertGetId([
            'title' => $title,
            'content' => $content,
            'fromUser' => $fromUser,
            'time' => date('Y-m-d H:i:s', time()),
            'qq' => $PersonData["qq"],
            //20210725 新增加入用户id
            'uid' => $uid,
            'code' => $randCode
        ]);


        $User = [];
        foreach ($input["toMail"] as $toMail)   //将发送人名单转化成每个用户的用户名
        {
            if (strstr($toMail, "-")) {
                $College = explode("-", $toMail);
                $CollegeData = $College[0];   //学院
                $Range = $College[1];         //发送人类别
                switch ($CollegeData) {
                    case "全体":
                        $SQL = Db::name('users');
                        break;
                    default:
                        $SQL = Db::name('users')->where("college", $CollegeData);
                }
                switch ($Range) {
                    case "全体":
                        $UserData = $SQL->select();
                        break;
                    case "青协":
                        $UserData = $SQL->where('auth', '<>', 0)->select();
                        break;
                }
                foreach ($UserData as $UserDatum) {
                    $User[] = $UserDatum["username"];
                }
            } else {
                if (!in_array($toMail, $User))
                    $User[] = $toMail;
            }
        }
        $success = 0;
        $error = 0;

        $PhoneNumbers = [];

        $params = [$fromUser, $content];

        foreach ($User as $usernamme)   //发件
        {
            $UserData = Db::name('users')->where('username', $usernamme)->find();
            if ($UserData) {
                $PhoneNumbers[] = $UserData["phone"];
                \db('message_queue')->insert([
                    'qq' => $UserData["qq"],
                    'name' => $UserData["name"],
                    'title' => $title,
                    'content' => $content,
                    'message_id' => $MsgId,
                    'uid' => $UserData['Id']
                ]);

                //原本的代码会在一次执行所有发送操作，导致大数据会超时，这次将要发送的消息放到数据库，优化效率
                //send_mail($UserData["qq"]."@qq.com",$UserData["name"],$title,$content);
                Db::name('msg_read')->insert([
                    'message_id' => $MsgId,
                    'read' => false,
                    'uid' => $UserData["Id"]
                ]);
                $success++;
            } else {
                $error++;
            }
        }
        Monitor('发送了内部通知');

        //尽可能发送短信吧
        /**
         * TODO 由于接口开放性问题，暂时不做
         */
//        $this->sendMessage($PhoneNumbers,$params);

        return json(["msg" => "操作完成，已加入消息队列"]);
    }

    /**
     * 发送消息队列
     */
    public function sendOneMessage()
    {

        ignore_user_abort();//关闭浏览器后，继续执行php代码

        set_time_limit(0);//程序执行时间无限制
        $sleep_time = 1;//多长时间执行一次

        while (true) {

            //获取数据库连接对象
            $databaseConnection=\db('message_queue');
            //取出最前面一条未发送的信息
            $oneMessageData = $databaseConnection->where('status', 0)->order('Id', 'asc')->find();
            if (!empty($oneMessageData)) {
                $Id = $oneMessageData['Id'];
                $qq = $oneMessageData['qq'];
                $name = $oneMessageData['name'];
                $title = $oneMessageData['title'];
                $content = $oneMessageData['content'];
                $message_id = $oneMessageData['message_id'];
                $uid = $oneMessageData['uid'];

                try {

                    //尝试发送邮件并更新状态，如果发送失败就抛出异常到数据库
                    send_mail($qq . "@qq.com", $name, $title, $content);
                    \db('message_queue')->where('Id', $Id)->update(['status' => 1]);
                } catch (\Exception $e) {
                    $error = $e->getMessage();
                    \db('message_queue')->where('Id', $Id)->update(['status' => -1, 'error' => $error]);
                }
            }else{
                break;
            }

            //关闭连接,防止占用线程
            $databaseConnection->close();

            sleep($sleep_time);//等待时间，进行下一次操作。

        }
    }

    public function MailBox()    //历史邮件列表
    {
        return $this->fetch('voluntary/MailBox');
    }

    /**
     * 邮件信息接口
     * @return Json 邮件信息的接口
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function MailJson()
    {
        $SafeCode = cookie('SafeCode');
//        $UserData = db('users')->where('SafeCode', $SafeCode)->find();
//        $MyMail = db('msg_read')->where('uid', $UserData['Id'])->select();
//
        //获取邮件信息
        $MyMail=db('msg_read')->alias("m")
            ->leftJoin("wyz_users u","u.Id=m.uid")
            ->field("u.*,m.*")
            ->where("u.SafeCode",$SafeCode)
            ->select();

        //初始化邮件数组
        $MailData = [];

        //如果存在搜索内容
        if (input('post.content')) {
            $content = input('post.content');
            foreach ($MyMail as $mail) {

                //构造查询条件
                $where = [
                    ['content', 'like', '%' . $content . '%'],
                    ['title', 'like', '%' . $content . '%'],
                    ['fromUser', 'like', '%' . $content . '%'],
                ];

                //闭包查询
                $mail_data = db('message')
                    ->where(function ($query) use ($mail) {
                        $query->where('Id', $mail['message_id']);
                    })->where(function ($query) use ($where) {
                        $query->whereOr($where);
                    })->find();

                //如果找到了数据
                if (!empty($mail_data)) {

                    //对内容进行过滤裁剪
                    $mail_data["content"] = htmlspecialchars(trim(strip_tags($mail_data["content"])));;
                    $mail_data["content"] = substr($mail_data["content"], 0, 40);
                    $mail_data["content"]=mb_convert_encoding($mail_data["content"], 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
                    $mail_data['read'] = $mail['read'];
                    $MailData[] = $mail_data;
                }

            }
        } else {
            foreach ($MyMail as $mail) {
                $mail_data = db('message')->where('Id', $mail['message_id'])->find();
                $mail_data["content"] = htmlspecialchars(trim(strip_tags($mail_data["content"])));;
                $mail_data["content"] = substr($mail_data["content"], 0, 40);
                $mail_data["content"]=mb_convert_encoding($mail_data["content"], 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');

                $mail_data['read'] = $mail['read'];
                $MailData[] = $mail_data;
            }
        }


        return json($MailData);
    }

    public function MailDetail()    //邮件详情
    {
        return $this->fetch('voluntary/MailDetail');
    }

    public function MailDetailJson()    //邮件详情信息接口
    {
        $Id = input('post.Id');
        $SafeCode = cookie('SafeCode');
        $PersonData = Db::name('users')->where('SafeCode', $SafeCode)->find();
        $mailData = Db::name('message')->where('Id', $Id)->find();
        $Belongs = Db::name('msg_read')->where(['message_id' => $Id, 'uid' => $PersonData['Id']])->find();
        if (empty($Belongs)) {
            return json([]);
        } else {
            Db::name('msg_read')
                ->where(['message_id' => $Id, 'uid' => $PersonData['Id']])
                ->update([
                    'read' => 1
                ]);
            return json($mailData);
        }
    }

    public function UploadImage()   //插入图片上传接口
    {
        $file = request()->file('file');
        if ($file) {
            $info = $file->move((new \think\Env)->get('root_path') . 'public/images');
            if ($info) {
                $dir = (new \think\Request)->domain() . '/images/' . $info->getSaveName();
                Monitor('上传了图片');
                return json(['dir' => $dir]);
            }
        }

        return json(['result'=>'error']);
    }

    public function copySchedule()   //导入课程表
    {
        return $this->fetch('voluntary/copySchedule');
    }

    public function updateSuperId()   //更新超级课程表信息
    {
        $superId = input('post.superId');
        $SafeCode = cookie('SafeCode');
        $sql = db('users')->where('SafeCode', $SafeCode)->limit(1)->update(['superId' => $superId]);
        if ($sql) {
            Monitor('更新了课程表信息');
            return json(['result' => 'success']);
        } else {
            return json(['result' => 'error']);
        }
    }


    /*------------------------------
     * 无课表获取相关事宜
     -------------------------------*/

    /**
     * @return mixed 查询课程表页面
     */
    public function searchSchedule()
    {
        return $this->fetch('voluntary/searchSchedule');
    }

    /**
     * 获取全体成员的无课表信息
     * @return Json 获取全部的无课表
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function ClassTable(): Json
    {

        $auth = ['普通学生', '青协主席', '会长', '网站管理员', '部长', '干事'];
        $sex = ['', '男', '女', '未知'];

        $SafeCode = cookie('SafeCode');

        //当前用户的学院
        $PersonCollege = \db('users')->where('SafeCode', $SafeCode)->value('college');

        //获取要查询的学年，学期，学号
        $week = input('param.week');
        $year = input('param.year');
        $term = input('param.term');

        //获取要查询的部门
        $department = input('post.department');


        if ($department == 'all') {
            //查询的用户的类型为全部
            $users = db('users')
                ->where('auth', '<>', '0')
                ->where('college', $PersonCollege)
                ->where('auth', '<>', '1')
                ->where('superId', '<>', '')
                ->whereNotNull('superId')
                ->select();

            $sids = \db('sid')->alias('s')
                ->field('u.*,s.*')
                ->leftJoin('wyz_users u', 's.uid=u.Id')
                ->where('u.auth', '<>', '0')
                ->where('u.college', $PersonCollege)
                ->where('u.auth', '<>', '1')
                ->select();
        } else {
            //查询的用户的类型为某个部门
            $users = db('users')
                ->where('auth', '<>', '0')
                ->where('department', $department)
                ->where('college', $PersonCollege)
                ->where('auth', '<>', '1')
                ->where('superId', '<>', '')
                ->whereNotNull('superId')
                ->select();

            $sids = \db('sid')->alias('s')
                ->field('u.*,s.*')
                ->leftJoin('wyz_users u', 's.uid=u.Id')
                ->where('u.auth', '<>', '0')
                ->where('u.department', $department)
                ->where('u.college', $PersonCollege)
                ->where('auth', '<>', '1')
                ->select();
        }


        //初始化课程表
        $ClassTable = [];

        //第0节课信息所在行为空
        $ClassTable[] = [];

        //初始化全部的课程表
        for ($i = 1; $i <= 12; $i++) {
            $tmp = [];
            $tmp[] = [];
            for ($j = 1; $j <= 7; $j++) {
                $tmp[] = [
                    'names' => [],
                    'num' => 0
                ];
            }
            $ClassTable[] = $tmp;
        }


        //遍历更新无课表（根据超级课程表）
        foreach ($users as $user) {

            //初始化有课数据
            for ($i = 1; $i <= 7; $i++) {
                for ($j = 1; $j <= 12; $j++) {
                    $ClassTableTmp[$i][$j] = false;
                }
            }

            $courseList = \db('table_json')->where([
                'uid' => $user['Id'],
                'year' => $year,
                'term' => $term,
                'type' => '0'
            ])->value('table_json');

            $courseList = json_decode($courseList, true);

            //循环查找课表
            if (is_array($courseList)){
                foreach ($courseList as $item) {

                    $smartPeriod = $item['smartPeriod'];  //课程所在周解码
                    $Periods = explode(" ", $smartPeriod);
                    if (in_array($week, $Periods))    //如果这周有课而且课在这个日期的话
                    {
                        //当前的星期几先存下来
                        $day = $item["day"];
                        $beginSection = $item["sectionStart"];
                        $endSection = $item["sectionEnd"];
                        for ($k = $beginSection; $k <= $endSection; $k++) {
                            $ClassTableTmp[$day][$k] = true;
                        }
                    }
                }
                //初始化有课数据
                for ($i = 1; $i <= 7; $i++) {
                    for ($j = 1; $j <= 12; $j++) {
                        //如果没课，就将其加入数组
                        if (!$ClassTableTmp[$i][$j]) {
                            $ClassTable[$j][$i]['names'][] = $user['name'];
                            $ClassTable[$j][$i]['num']++;
                        }
                    }
                }
            }
        }


        //初始化有课数据
        for ($i = 1; $i <= 7; $i++) {
            for ($j = 1; $j <= 12; $j++) {
                $ClassTable[$j][$i]['names'][] = "以下为教务系统信息：";
            }
        }

        foreach ($sids as $sid) {

            //初始化有课数据
            for ($i = 1; $i <= 7; $i++) {
                for ($j = 1; $j <= 12; $j++) {
                    $ClassTableTmp[$i][$j] = false;
                }
            }


            $courseList = \db('table_json')->where([
                'uid' => $sid['uid'],
                'year' => $year,
                'term' => $term,
                'type' => '1',
            ])->where('table_json', '<>', '[]')
                ->where('table_json', '<>', 'null')
                ->whereNotNull("table_json")
                ->value('table_json');



            $courseList = json_decode($courseList, true);

            //根据教务系统信息更新无课表数据
            if (is_array($courseList)) {
                foreach ($courseList as $oneCourse) {

                    $weekDatum = $oneCourse["zcd"];

                    $res=$this->weekInRange($week, $weekDatum);
                    //如果当前的课在这个周有的话
                    if ($res) {
                        $xqj = $oneCourse["xqj"];
                        $jcs = $oneCourse["jcs"];

                        $jcs = explode("-", $jcs);

                        if (count($jcs) <= 1) {
                            $ClassTableTmp[(int)$xqj][(int)$jcs[0]] = true;
                        } else {
                            for ($i = (int)$jcs[0]; $i <= (int)$jcs[1]; $i++) {
                                $ClassTableTmp[(int)$xqj][$i] = true;
                            }
                        }

                    }

                }
            }

            //初始化有课数据
            for ($i = 1; $i <= 7; $i++) {
                for ($j = 1; $j <= 12; $j++) {
                    //如果没课，就将其加入数组
                    if (!$ClassTableTmp[$i][$j]) {
                        $ClassTable[$j][$i]['names'][] = $sid['name'];
                        $ClassTable[$j][$i]['num']++;
                    }
                }
            }

        }

        Monitor('搜索了无课表');
        return json(['result' => 'success', 'table' => $ClassTable]);
    }

    /**
     * 判断某个课程是否在当前查询的周中
     * @param $week int 当前查询的周
     * @param $weekDatum
     * @return false
     */
    private function weekInRange($week, $weekDatum): bool
    {
        //先假设当前查询的日期不在当前课的范围内


        //使用字符串分割，判断有没有逗号，有逗号顺便转化为数组
        $weekData = explode(",", $weekDatum);


        if (count($weekData) <= 1) {

            //此时经过分割以后变量已经成了单元素的数组
            $weekData = $weekData[0];

            //如果是双周，但我查询的数据是单周，就肯定不在里面，返回错误
            if (substr($weekData, -5) === "(双)") {


                if ((int)$week % 2 === 1) {
                    return false;
                }

                //如果确实，先处理一下，使其成为类似1-7或者7的形式
                str_replace("周(双)", "", $weekData);

            }

            //如果是单周，但我查询的数据是双周，就跳过
            if (substr($weekData, -5) === "(单)") {

                if ((int)$week % 2 === 0) {
                    return false;
                }

                //如果确实，先处理一下，使其成为类似1-7或者7的形式
                str_replace("周(单)", "", $weekData);

            }

            /*
             * 到目前，程序已经去除掉了后面的中文字符
             * 也完成了判断单双周
             * 现在只需要判断当前周是否在范围内即可
             */

            $weekData = explode("-", $weekData);

            //如果当前只是7的形式
            if (count($weekData) <= 1) {
                if ((int)$weekData[0] == (int)$week) {
                    return true;
                } else {
                    return false;
                }
            } else {
                //否则当前就是1-7的形式
                //则只需要判断是不是在范围里面就行了
                if ((int)$weekData[0] <= (int)$week && (int)$week <= (int)$weekData[1]) {
                    return true;
                } else {
                    return false;
                }

            }


        } else {
            //否则需要循环判断
            for ($i = 0; $i < count($weekData); $i++) {
                $weekDatum = $weekData[$i];

                //如果是双周，但我查询的数据是单周，就肯定不在里面，返回错误
                if (substr($weekDatum, -5) === "(双)") {

                    if ((int)$week % 2 === 1) {
                        continue;
                    }

                    //如果确实，先处理一下，使其成为类似1-7或者7的形式
                    str_replace("周(双)", "", $weekDatum);

                }

                //如果是单周，但我查询的数据是双周，就跳过
                if (substr($weekDatum, -5) === "(单)") {

                    if ((int)$week % 2 === 0) {
                        continue;
                    }

                    //如果确实，先处理一下，使其成为类似1-7或者7的形式
                    str_replace("周(单)", "", $weekDatum);

                }

                /*
                 * 到目前，程序已经去除掉了后面的中文字符
                 * 也完成了判断单双周
                 * 现在只需要判断当前周是否在范围内即可
                 */

                $weekDatum = explode("-", $weekDatum);

                //如果当前只是7的形式
                if (count($weekDatum) <= 1) {
                    if ((int)$weekDatum[0] == (int)$week) {
                        return true;
                    }
                } else {
                    //否则当前就是1-7的形式
                    //则只需要判断是不是在范围里面就行了
                    if ((int)$weekDatum[0] <= (int)$week && (int)$week <= (int)$weekDatum[1]) {
                        return true;
                    }

                }

            }

            //循环判读无果就肯定是不在这周了
            return false;
        }


    }

    /**
     * 更新无课表
     */
    public function updateTable()
    {

        ignore_user_abort();//关闭浏览器后，继续执行php代码

        set_time_limit(0);//程序执行时间无限制

        $databaseConnection=db('users');

        //根据无课表更新教务系统的无课表信息
        $users = $databaseConnection
            ->where('auth', '<>', '0')
            ->where('auth', '<>', '1')
            ->where('superId', '<>', '')
            ->whereNotNull('superId')
            ->select();

        //关闭连接
        $databaseConnection->close();

        $now = new DateTime();
        $year = $now->format("Y");

        foreach ($users as $user) {

            //不通过教务系统来访问，传入账号密码为空
            $robot = new Robot($user['Id'], '', '');

            $superId = $user['superId'];

            //更新两个学期的课表
            try {

                $robot->getScheduleBySuperId($superId, $year, '1');
                $robot->getScheduleBySuperId($superId, $year, '2');
            } catch (Exception $e) {
            }

            unset($robot);

        }

        $databaseConnection=db('sid');

        //根据教务系统更新教务系统的无课表信息
        $sids = $databaseConnection->alias('s')
            ->leftJoin('wyz_users u', 's.uid=u.Id')
            ->field('s.*')
            ->select();

        $databaseConnection->close();

        foreach ($sids as $sid) {

            $robot = new Robot($sid['uid'], $sid['sid'], $sid['pwd']);

            //更新两个今年第一第二学期的课程表
            try {
                $robot->getSchedule($year);
            }catch (Exception $e) {
                \db('log')->insert(['message'=>$e->getMessage()]);
            }
            try {
                $robot->getSchedule($year, '2');
            } catch (Exception $e) {
                \db('log')->insert(['message'=>$e->getMessage()]);
            }

            try {
                $robot->getScore($year);
            }catch (Exception $e) {
                \db('log')->insert(['message'=>$e->getMessage()]);
            }

            try {
                $robot->getScore($year, '2');
            } catch (Exception $e) {
                \db('log')->insert(['message'=>$e->getMessage()]);
            }
            try {
                $robot->getScore((int)$year - 1);
            }catch (Exception $e) {
                \db('log')->insert(['message'=>$e->getMessage()]);
            }
            try {
                $robot->getScore((int)$year - 1, '2');
            }catch (Exception $e) {
                \db('log')->insert(['message'=>$e->getMessage()]);
            }


            unset($robot);

        }


    }

    /**
     * 无课人员信息接口
     * @return Json 当前课无课人员的json数据
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function WithoutClassJson()
    {
        $auth = ['普通学生', '青协主席', '会长', '网站管理员', '部长', '干事'];
        $sex = ['', '男', '女', '未知'];

        $SafeCode = cookie('SafeCode');

        //当前用户的学院
        $PersonCollege = \db('users')->where('SafeCode', $SafeCode)->value('college');

        //第几周
        $week = input('post.week');

        //星期几
        $weekDay = input('post.weekDay');

        //第几节课
        $class = input('post.class');

        //学年学期
        $year = input('post.year');
        $term = input('post.term');


        //查询的用户的类型
        $users = db('users')->alias("u")
            ->field("u.*,t.*")
            ->rightJoin("wyz_table_json t", "t.uid=u.Id")
            ->where('u.auth', '<>', '0')
            ->where('u.college', $PersonCollege)
            ->where('u.auth', '<>', '1')
            ->where('u.superId', '<>', '')
            ->where("t.year", $year)
            ->where("t.term", $term)
            ->where("t.type", "0")
            ->whereNotNull('superId')
            ->select();

        //无课人员列表
        $NoCLassUser = [];
        foreach ($users as $user) {

            //从数据库中获取课表的json对象
            $jsonData = $user["table_json"];
            $courseList = json_decode($jsonData, true);

            //假设当前人没课
            $hasClass = false;
            foreach ($courseList as $item) {

                //课程所走的周，对所在周的数据解析成数组
                $smartPeriod = $item['smartPeriod'];
                $Periods = explode(" ", $smartPeriod);

                //如果当前查询的周在查询的这个周的这个日期，就判课程节次是否包含在里面
                if (in_array($week, $Periods) && $weekDay == $item["day"])
                {
                    $beginSection = $item["sectionStart"];
                    $endSection = $item["sectionEnd"];
                    if ($class >= $beginSection && $class <= $endSection)  //是这几节课吗？
                    {
                        $hasClass = true;
                        break;
                    }
                }
            }

            //如果确实无课，就将此人加入列表
            if (!$hasClass) {

                //构造此人的信息数组
                $userData = [
                    "name" => $user['name'],
                    "username" => $user['username'],
                    'sex' => $sex[$user['sex']],
                    'qq' => $user['qq'],
                    'phone' => $user['phone'],
                    'department' => $user['department'],
                    'auth' => $auth[$user['auth']]
                ];

                $NoCLassUser[] = $userData;

                unset($userData);
            }
        }

        //根据教务系统获取课表
        $sids = db('users')->alias("u")
            ->field("u.*,t.*")
            ->rightJoin("wyz_table_json t", "t.uid=u.Id")
            ->where('u.auth', '<>', '0')
            ->where('u.college', $PersonCollege)
            ->where('u.auth', '<>', '1')
            ->where("t.year", $year)
            ->where("t.term", $term)
            ->where("t.type", "1")
            ->select();

        foreach ($sids as $sid){
            //从数据库中获取课表的json对象
            $jsonData = $sid["table_json"];
            $courseList = json_decode($jsonData, true);

            //假设当前人没课
            $hasClass = false;

            if (is_array($courseList)){
                foreach ($courseList as $oneCourse) {

                    $weekDatum=$oneCourse["zcd"];

                    if ($this->weekInRange($week,$weekDatum)){

                        //当前课在星期几
                        $xqj = (int)$oneCourse["xqj"];

                        //如果查询的课也在这个星期的话
                        if((int)$weekDay == $xqj){

                            //课程节次信息
                            $jcs = $oneCourse["jcs"];

                            //使用-分开节次信息为两个部分，一个为开始节次，一个为结束节次
                            //也可能是只有一节课，那就直接为课程节次
                            $jcs = explode("-", $jcs);

                            //如果只有一节课
                            if (count($jcs) <= 1) {

                                //判断查询的课是不是这节课
                                if((int)$jcs[0] == (int)$class){

                                    $hasClass=true;

                                    break;
                                }
                            } else {
                                //不止一节课

                                //判断查询的课在不在这节课的区间内
                                if((int)$jcs[0] <= (int)$class && (int)$class <= (int)$jcs[1]){

                                    $hasClass=true;

                                    break;
                                }

                            }


                        }

                    }


                }

                //如果确实无课，就将此人加入列表
                if (!$hasClass) {

                    //构造此人的信息数组
                    $userData = [
                        "name" => $sid['name']."（教）",
                        "username" => $sid['username'],
                        'sex' => $sex[$sid['sex']],
                        'qq' => $sid['qq'],
                        'phone' => $sid['phone'],
                        'department' => $sid['department'],
                        'auth' => $auth[$sid['auth']]
                    ];

                    $NoCLassUser[] = $userData;

                    unset($userData);
                }
            }

        }

        return json($NoCLassUser);
    }

    public function WithoutClass()  //无课人员列表
    {
        return $this->fetch('voluntary/Withoutclass');
    }

    public function SearchNoclass() //无课表搜索
    {
        return $this->fetch('voluntary/SearchNoClass');
    }

    public function editDescription()   //编辑我的青协描述信息
    {
        return $this->fetch('voluntary/editDescription');
    }


    /*
     * 青协历史志愿者榜单
     */

    public function getDescriptionJson()    //获取我的描述信息接口
    {
        $SafeCode = cookie('SafeCode');
        $User = \db('voluntary')->alias('a')
            ->join('wyz_users b', 'a.uid=b.Id')
            ->where('b.SafeCode', $SafeCode)->find();

        //如果存在描述，则返回数据，否则返回空
        if (!empty($User)) {
            return json($User);
        } else {
            return json(['description' => '']);
        }


    }

    public function editDescriptionJson()    //编辑描述信息接口
    {
        $auth = ['', '主席', '会长', '管理员', '部长', '干事'];
        $content = input('post.content');
        $SafeCode = cookie('SafeCode');
        $UserData = \db('users')->where('SafeCode', $SafeCode)->find();
        $uid = $UserData['Id'];
        $User = \db('voluntary')->where('uid', $uid)->find();

        //如果不存在
        if (!empty($User)) {
            $sql = \db('voluntary')->where('uid', $uid)->update(['description' => $content, 'job' => $auth[$UserData['auth']]]);
        } else {
            $sql = \db('voluntary')->insert(['name' => $UserData['name'], 'uid' => $uid, 'description' => $content, 'job' => $auth[$UserData['auth']]]);
        }
        if ($sql) {
            Monitor('编辑了自己的青协信息');
            return json(['result' => 'success']);
        } else {
            return json(['result' => 'error']);
        }


    }

    /**发送短信
     * @param array $phoneNumbers 号码的集合
     * @param array $data 数据的集合（根据模板）
     * @return string 发送结果
     */
    private function sendMessage($phoneNumbers = [], $data = [])
    {
        try {
            //实例化发件库
            $msender = new SmsMultiSender($this->appid, $this->appkey);

            //执行发送并返回结果
            return $msender->sendWithParam("86", $phoneNumbers, $this->templateId, $data, $this->smsSign, "", "");

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}